import axios from 'axios'
import qs from 'qs'
const baseUrl = ''
let loading

export default class Axios {
  static get (options) {
    return new Promise((resolve, reject) => {
      axios.get(baseUrl + options.url, {
        params: (options.data && options.data.params) ? options.data.params : '',
        timeout: 15000
      }).then(response => {
        if (response.status === 200) {
          let res = response.data
          if (res.code === 0) {
            resolve(res)
          } else {
            // 错误提示
          }
        } else {
          reject(response.data)
        }
      }).catch(error => {
        // 请求出错，在这里设置
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
          if (options.data && options.data.isLoading !== false) {
            loading = document.getElementById('ajaxLoading')
            loading.style.display = 'none'
          }
          // return service.request(originalRequest);//例如再重复请求一次
        }
      })
    })
  }

  static post (options) {
    return new Promise((resolve, reject) => {
      axios.post(baseUrl + options.url, {
        ...qs.stringify(options.data.params),
        timeout: 15000
      }).then(response => {
        if (response.status === 200) {
          let res = response.data
          if (res.code === 0) {
            resolve(res)
          } else {
            // 错误提示
          }
        } else {
          reject(response.data)
        }
      }).catch(error => {
        // 请求出错，在这里设置
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
          if (options.data && options.data.isLoading !== false) {
            loading = document.getElementById('ajaxLoading')
            loading.style.display = 'none'
          }
          // return service.request(originalRequest);//例如再重复请求一次
        }
      })
    })
  }
}
